<?php
namespace linggong;
use Kuaidi\appkey;
use Kuaidi\data;
use Kuaidi\DataSign签名;
use Kuaidi\url响应返回的html;

/**
 * Created by PhpStorm.
 * User: 农夫
 * Date: 2019/03/11
 * Time: 16:08
 */
class Linggong
{
    private $app_id = null; //电商ID
    private $app_secret = null; //电商加密私钥，快递鸟提供，注意保管，不要泄漏
    private $api_url = null; //请求url，正式环境地址：http://api.kdniao.com/api/Eorderservice    测试环境地址：http://testapi.kdniao.com:8081/api/EOrderService

    public function __construct()
    {
        $this->app_id = settings('transfer_app_id');
        $this->app_secret = settings('transfer_app_secret');
        $this->api_url = 'http://rmtt.zhihui888.cn/outapi/';
    }

    public function getToken()
    {
        $data = [
            'appid' => $this->app_id,
            'appsecret' => $this->app_secret,
        ];
        $res = $this->sendPost('access_token',$data);
        return $res['data']['access_token'];
    }

    public function addWork($data)
    {
        $headers[] = 'Authori-zation:Bearer '.$this->getToken();
        $res = $this->sendPost('worker/create',$data,$headers);
        return $res;
    }

    public function sendProfit($data)
    {
        $headers[] = 'Authori-zation:Bearer '.$this->getToken();
        $res = $this->sendPost('profit/send',$data,$headers);
        return $res;
    }
    public function sendPost($url,$data = [],$headers = [])
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $this->api_url.$url); // 要访问的地址
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS,  $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            return 'Error POST'.curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return json_decode($result,true); // 返回数据

    }


}
